package br.com.intelsys.basics.spring;

import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DictionaryProperties extends Properties {
	private static final long serialVersionUID = 7994183963995668727L;
	private static final String PROPERTIES_FILE = "content.properties";
	private static final String PROPERTIES_FILE_PACKAGE = "/etc/content/";
	private static final String PROPERTIES = ".properties";
	private static final String CONTENT = "content-";
	private static Set<String> propReadSet;
	private boolean mainPropLoaded;

	private static Log log = LogFactory.getLog(DictionaryProperties.class);

	public DictionaryProperties() {
		this(null);
	}

	public DictionaryProperties(String ctrlEntity) {
		loadProperties(null);
		if (ctrlEntity != null) {
			loadProperties(ctrlEntity);
		}
	}

	public void loadProperties(String ctrlEntity) {
		if (log.isDebugEnabled()) {
			log.debug("Carregando o arquivo de propriedades " + PROPERTIES_FILE);
		}
		propReadSet = new HashSet<String>();
		if (ctrlEntity == null && !mainPropLoaded || !propReadSet.contains(propReadSet)) {
			propReadSet.add(ctrlEntity);
			String propertiesFile = getPropertiesFile(ctrlEntity);
			try {
				load(PathFinder.class.getResourceAsStream(propertiesFile));
				if (ctrlEntity == null) {
					mainPropLoaded = true;
				}
			} catch (NullPointerException e) {
				if (log.isDebugEnabled()) {
					log.debug("O arquivo de propriedades " + propertiesFile + " nao foi encontrado no classpah.");
				}
			} catch (IOException e) {
				if (log.isDebugEnabled()) {
					log.debug("Erro ao ler o arquivo de propriedades " + propertiesFile);
				}
			}
		}
	}

	private static String getPropertiesFile(String ctrlEntity) {
		StringBuilder sb = new StringBuilder();
		sb.append(PROPERTIES_FILE_PACKAGE);
		if (ctrlEntity == null) {
			sb.append(PROPERTIES_FILE);
		} else {
			sb.append(CONTENT);
			sb.append(ctrlEntity);
			sb.append(PROPERTIES);
		}
		return sb.toString();
	}

	public String getProperty(String key) {
		String ret = super.getProperty(key);
		return ret != null ? ret : key;
	}

	public static String insertParamsIntoText(Properties property, String content, String... params) {
		int j = 0;
		if (params != null) {
			for (String param : params) {
				content = content.replace("{" + (j++ + 1) + "}", param != null ? property.getProperty(param, param) : "");
			}
		}
		return content;
	}

	public String getProp(String key, String... params) {
		String prop = getProperty(key);
		if (params != null) {
			for (int i = 0; i < params.length; i++) {
				prop = prop.replaceAll("\\{" + (i + 1) + "\\}", params[i]);
			}
		}
		return prop;
	}
}
